﻿using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Folding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor
{
    /// <summary>
    /// 此类用以定义 PlainTextEditor 编辑器的折叠区。
    /// </summary>
    class PlainFoldingStrategy : AbstractFoldingStrategy
    {
        private ICSharpCode.AvalonEdit.TextEditor edit;
        /// <summary>
        /// 要应用折叠功能的编辑器。
        /// </summary>
        public ICSharpCode.AvalonEdit.TextEditor Edit { get { return this.edit; } }

        /// <summary>
        /// [构造方法]创建一个新的折叠区。
        /// </summary>
        public PlainFoldingStrategy(ICSharpCode.AvalonEdit.TextEditor edit)
        {
            this.edit = edit;
        }

        /// <summary>
        /// 为特定文档创建 NewFolding 对象集。
        /// </summary>
        public override IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
        {
            firstErrorOffset = -1;
            return CreateNewFoldings(document);
        }

        /// <summary>
        /// 为 CSS 文档创建 NewFolding 对象集。
        /// </summary>
        public IEnumerable<NewFolding> CreateNewFoldings(ITextSource document)
        {
            List<NewFolding> newFoldings = new List<NewFolding>();

            #region 添加环境变量自定义折叠块
            List<HeaderInfo> preEValuesInfos = new List<HeaderInfo>();

            var trimChars = new char[] { ' ', '　', '\t', };

            for (int i = 1; i <= edit.LineCount; i++)
            {
                var line = edit.Document.GetLineByNumber(i);

                string text = edit.Document.GetText(line.Offset, line.Length);

                text = text.TrimEnd(trimChars);
                if (text.StartsWith("/*") == false || text.EndsWith("*/") == false) continue;

                var headerText = GetHeaderOfEnviromentValue(text);
                var contentText = GetCommentOfEnviromentValue(text);

                var newEvalueInfo = new HeaderInfo()
                {
                    HeaderText = headerText,
                    ContentText = contentText,
                    Length = headerText.Length,
                    Offset = line.Offset,
                    EndOffset = line.EndOffset,
                };

                if (preEValuesInfos.Count <= 0)
                {
                    preEValuesInfos.Add(newEvalueInfo);
                    continue;
                }

                for (int j = preEValuesInfos.Count - 1; j >= 0; j--)
                {
                    if (newEvalueInfo.Length <= preEValuesInfos[j].Length)
                    {
                        var endOffset = newEvalueInfo.Offset - 2;  // -2是\r\n的宽度

                        //如果在这个标题只有一行，不折叠
                        if (endOffset > preEValuesInfos[j].EndOffset)
                        {
                            var newFolding = new NewFolding(preEValuesInfos[j].Offset, newEvalueInfo.Offset - 2)
                            {
                                Name = $"/*{preEValuesInfos[j].HeaderText}*/",
                            };
                            newFoldings.Add(newFolding);
                        }
                        preEValuesInfos.RemoveAt(j);
                    }
                }

                preEValuesInfos.Add(newEvalueInfo);
            }

            //到最后一行，看看要不要添加折叠块。
            if (preEValuesInfos.Count > 0)
            {
                var lastLine = this.edit.Document.GetLineByNumber(this.edit.Document.LineCount);
                if (lastLine != null)
                {
                    var lastLineText = this.edit.Document.GetText(lastLine).TrimEnd(trimChars);

                    if (lastLineText.StartsWith("/*") == false)
                    {
                        for (int j = preEValuesInfos.Count - 1; j >= 0; j--)
                        {
                            var endOffset = edit.Document.Lines.Last().Offset;//最后一行，没有\r\n，不用 - 2;

                            //如果在这个标题只有一行，不折叠
                            if (endOffset > preEValuesInfos[j].EndOffset)
                            {
                                newFoldings.Add(new NewFolding(preEValuesInfos[j].Offset, endOffset)
                                {
                                    Name = $"/*{preEValuesInfos[j].HeaderText}*/",
                                });
                            }
                            preEValuesInfos.RemoveAt(j);
                        }
                    }
                }
            }
            #endregion

            newFoldings.Sort((a, b) => a.StartOffset.CompareTo(b.StartOffset));
            return newFoldings;
        }

        private string GetCommentOfEnviromentValue(string text)
        {
            if (string.IsNullOrWhiteSpace(text)) return "";

            var start = text.IndexOf("/*");
            if (start < 0) return "";

            var end = text.IndexOf("*/", start + 2);
            if (end < 0) return "";

            text = text.Substring(start + 2, end - start - 2);

            var mid = text.IndexOf("-");
            if (mid < 0) return text;  // 没有注释

            return text.Substring(0, mid).Trim(new char[] { ' ', '　', '\t', });
        }

        private string GetHeaderOfEnviromentValue(string text)
        {
            if (string.IsNullOrWhiteSpace(text)) return "";

            var start = text.IndexOf("/*");
            if (start < 0) return "";

            var end = text.IndexOf("*/", start + 2);
            if (end < 0) return "";

            text = text.Substring(start + 2, end - start - 2);

            var mid = text.IndexOf("-");
            if (mid < 0) return text;  // 没有注释

            return text.Substring(mid).Trim(new char[] { ' ', '　', '\t', });
        }
    }
}
